//
//  SampleViewController.m
//  OperationPro
//
//  Created by yaxue wang on 2016/12/19.
//  Copyright © 2016年 展鸿科技. All rights reserved.
//

#import "SampleViewController.h"
#import "TPKeyboardAvoidingTableView.h"
@interface SampleViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
@property(nonatomic,strong)TPKeyboardAvoidingTableView*table;
@property(nonatomic,strong) NSArray *ar;
@property(nonatomic,strong) NSArray *placeAr;
@property(nonatomic) NSInteger sectionNum;
@property(nonatomic,strong)UILabel *totalLab;
@property(nonatomic,strong)NSMutableArray*dataAr;

@end

@implementation SampleViewController
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    _sectionNum=0;

}
- (void)initView
{
    [super initView];

    self.navBar.leftView = nil;
    self.navBar.bgColor =[UIColor clearColor];
    self.hide=YES;
    UIView *narView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, WindowWidth, 64)];
    narView.backgroundColor =MainColor;
    [self.view addSubview:narView];
    
    UIView *backView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, 100, 64)];
    [narView addSubview:backView];
    [backView bk_whenTapped:^{
        [self backController];
    }];
    
    UIImage *icoBack = [UIImage imageNamed:@"Ico_nar_backWhite"];
    UIImageView *imgBack = [[UIImageView alloc] initWithFrame:CGRectMake(15, 33, icoBack.size.width, icoBack.size.height)];
    imgBack.image=icoBack;
    [backView addSubview:imgBack];
    
    UILabel *backTitle = [[UILabel alloc] init];
    backTitle.frame=CGRectMake(CGRectGetMaxX(imgBack.frame) + 5, 20, 50 - imgBack.frame.size.width,44);
    
    [backTitle setText:@"返回"];
    [backTitle setTextColor:[UIColor whiteColor]];
    [backTitle setFont:F(14)];
    [backView addSubview:backTitle];
    
    UILabel *titleLab =[[UILabel alloc]init];
    [narView addSubview:titleLab];
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(narView);
        make.top.equalTo(narView).offset(30);
    }];
    titleLab.font =F(16);
    titleLab.textColor =[UIColor whiteColor];
    titleLab.text=@"采购单";
    
    UIView *ringView=[[UIView alloc]initWithFrame:CGRectMake(WindowWidth-80, 0, 80, 64)];
    [narView addSubview:ringView];
    UILabel *rightLab =[[UILabel alloc]initWithFrame:CGRectMake(0, 20, 65, 44)];
    rightLab.text =@"发送";
    rightLab.textAlignment=NSTextAlignmentRight;
    rightLab.font=F(14);
    rightLab.textColor=[UIColor whiteColor];
    rightLab.userInteractionEnabled=YES;
    [ringView addSubview:rightLab];
    [ringView bk_whenTapped:^{
        double doubleTotal;
        doubleTotal=0.00;
        for (int i=0; i<_dataAr.count; i++) {
            NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:self.dataAr[i]];
            //名称
            if ([[dic allKeys] containsObject:@"name"]) {
                
                if ([[dic objectForKey:@"name"] isEqualToString:@""]) {
                    [CClass showMessage:@"请输入物品名称！"];
                    return ;
                }
            }else
            {
                [CClass showMessage:@"请输入物品名称！"];
                return ;
                
            }
            //规格
            if ([[dic allKeys] containsObject:@"spec"]) {
                
                
            }else
            {
                [dic setObject:@"" forKey:@"spec"];
                
            }
            //数量
            if ([[dic allKeys] containsObject:@"count"]) {
                
                if ([[dic objectForKey:@"count"] isEqualToString:@""]) {
                    [CClass showMessage:@"请输入物品数量！"];
                    return ;
                }else
                {
                    if([[dic objectForKey:@"count"] integerValue]==0)
                    {
                        [CClass showMessage:@"数量不能为零！"];
                        return ;
                    }
                }
            }else
            {
                [CClass showMessage:@"请输入物品数量！"];
                return ;
                
            }
            //总价
            if ([[dic allKeys] containsObject:@"total_price"]) {
                
                if ([[dic objectForKey:@"total_price"] isEqualToString:@""]) {
                    [CClass showMessage:@"请输入总价！"];
                    return ;
                }else
                {
                    if([[dic objectForKey:@"total_price"] isEqualToString:@"0.00"]||[[dic objectForKey:@"total_price"] isEqualToString:@"0.0"]||[[dic objectForKey:@"total_price"] isEqualToString:@"0"])
                    {
                        [CClass showMessage:@"总价不能为零！"];
                        return ;
                        
                    }else
                    {
                        doubleTotal+=[[dic objectForKey:@"total_price"] doubleValue];
                        
                    }
                    
                    
                }
            }else
            {
                [CClass showMessage:@"请输入总价！"];
                return ;
                
            }
            
            //用途
            if ([[dic allKeys] containsObject:@"purpose"]) {
                
                if ([[dic objectForKey:@"purpose"] isEqualToString:@""]) {
                    [CClass showMessage:@"请输入用途！"];
                    return ;
                }
            }else
            {
                [CClass showMessage:@"请输入用途！"];
                return ;
                
            }
            
            //备注
            if ([[dic allKeys] containsObject:@"remark"]) {
                
                
            }else
            {
                [dic setObject:@"" forKey:@"remark"];
                
            }
            [self.dataAr replaceObjectAtIndex:i withObject:dic];
            
        }
        
        NSMutableDictionary *dataDic=[[NSMutableDictionary alloc]init];
        [dataDic setObject:_dataAr forKey:@"list"];
        [dataDic setObject:self.orderUuid forKey:@"order_uuid"];
        [dataDic setObject:[NSString stringWithFormat:@"%2f",doubleTotal] forKey:@"total_price"];
        
        NSData *data=[NSJSONSerialization dataWithJSONObject:dataDic options:NSJSONWritingPrettyPrinted error:nil];
        NSString *jsonString=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        ringView.userInteractionEnabled=NO;
        [self setIsLoading:YES];
        [CClass HttpRequestTask:YES withUrl:@"purchase_create" withData:@{@"data":jsonString} notifyError:YES onSuccess:^(BaseModel *model) {
            [CClass showLittleTimeMessage:@"发送成功，等待报修人确认" completion:^{
                [self backController];
                [self setIsLoading:NO];
                
            }];
        } onError:^(BaseModel *model) {
            ringView.userInteractionEnabled=YES;
            [self setIsLoading:NO];


        }];
 
    }];
    

    _dataAr=[NSMutableArray array];
    [_dataAr addObject:@{}];

//    [self.navBar createRightBtn:@"发送" block:^{
//      
//    }];
    _ar=[NSArray arrayWithObjects:@"物品名称",@"规格",@"数量",@"总价(元)",@"用途",@"备注", nil];
    _placeAr=[NSArray arrayWithObjects:@"请输入物品名称",@"请输入物品规格",@"请输入物品数量",@"请输入物品总价",@"请输入物品用途",@"请输入备注", nil];//@"请输入（必填）",@"请输入",@"请输入（必填）",@"请输入（必填）",@"请输入（必填）",@"请输入",
    _table =[[TPKeyboardAvoidingTableView alloc]initWithFrame:CGRectMake(0, 64, WindowWidth,WindowHeight-64)];
    _table.delegate =self;
    _table.dataSource =self;
    _table.backgroundColor =C(@"f0f0f0");
    _table.separatorStyle =UITableViewCellSelectionStyleNone;
    [self.view addSubview:_table];
   _table.tableFooterView=[self footTableView];
  


}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 6;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _sectionNum+1;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];

        UILabel *titleLab=[[UILabel alloc]initWithFrame:CGRectMake(10, 0, 65, 44)];
        titleLab.tag=100;
        titleLab.font=F(13);
        titleLab.textColor=C(@"a1a1a1");
        [cell.contentView addSubview:titleLab];
        UILabel *startLab=[[UILabel alloc]initWithFrame:CGRectMake(75, 0, 18, 44)];
        startLab.tag=600;
        startLab.font=F(14);
        startLab.textColor=MainColor;
        [cell.contentView addSubview:startLab];
        
        CTextField *textField =[[CTextField alloc]initWithFrame:CGRectMake(75+18, 0, WindowWidth-75-18-5, 44)];
        textField.font =F(13);
        textField.inputType=CTextFieldInputTypeDefault;
        textField.delegate=self;
        textField.returnKeyType = UIReturnKeyNext;
        textField.tag =200;
        textField.textColor=C(@"666666");
        [cell.contentView addSubview:textField];

        UILabel *line1 =[[UILabel alloc]initWithFrame:CGRectMake(0,44-0.5, WindowWidth, 0.5)];
        line1.tag =400;
        line1.backgroundColor=LineColor;
        [cell.contentView addSubview:line1];

        
    }
    UILabel *nameLab=[cell viewWithTag:100];
    nameLab.text=[_ar objectAtIndex:indexPath.row];
    UILabel *startLab=[cell viewWithTag:600];
    if(indexPath.row==0||indexPath.row==2||indexPath.row==3||indexPath.row==4){
        startLab.text=@"*";
    }else
    {
        startLab.text=@"";
 
    }

    CTextField *textField =[cell viewWithTag:200];
    if(indexPath.row==2){
        textField.inputType=CTextFieldInputTypeNum;
        [textField setMaxLength:6 LengthChangeBlock:nil];

        
        
    }else if(indexPath.row==3)
    {
        textField.inputType=CTextFieldInputTypeMoney;

        [textField setBk_didEndEditingBlock:^(UITextField *tfd) {
            double totalDoubleDetele = 0.0;
            for (int i=0; i<_dataAr.count; i++) {
                NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:self.dataAr[i]];
                //名称
                if ([[dic allKeys] containsObject:@"total_price"]) {
                    
                    if ([[dic objectForKey:@"total_price"] isEqualToString:@""]) {
                    }else
                    {
                        totalDoubleDetele+=[[dic objectForKey:@"total_price"] doubleValue];
                    }
                }else
                {
                    
                    
                }
            }
            _totalLab.text=[NSString stringWithFormat:@"合计（元）：%.2f",totalDoubleDetele];
            
        }];

        
        
    }else if(indexPath.row==5)
    {
        //备注
        textField.inputType=CTextFieldInputTypeDefault;
        [textField setMaxLength:20 LengthChangeBlock:nil];
  
    }else
    {
        textField.inputType=CTextFieldInputTypeDefault;
        [textField setMaxLength:10 LengthChangeBlock:nil];

    }
    textField.placeholder=[_placeAr objectAtIndex:indexPath.row];

     NSMutableDictionary *dataDic=[NSMutableDictionary dictionaryWithDictionary:self.dataAr[indexPath.section]];
     //名称
   
     if (indexPath.row==0) {
         if ([[dataDic allKeys] containsObject:@"name"]) {
             textField.text= [dataDic objectForKey:@"name"];

         }else
         {
             textField.text=@"";
         }
     }else if (indexPath.row==1)
     {
         if ([[dataDic allKeys] containsObject:@"spec"]) {
             textField.text= [dataDic objectForKey:@"spec"];
             
         }else
         {
             textField.text=@"";
         }
     }else if (indexPath.row==2)
     {
         if ([[dataDic allKeys] containsObject:@"count"]) {
             textField.text= [dataDic objectForKey:@"count"];
             
         }else
         {
             textField.text=@"";
         }
     }else if (indexPath.row==3)
     {
         if ([[dataDic allKeys] containsObject:@"total_price"]) {
             textField.text= [dataDic objectForKey:@"total_price"];
             
         }else
         {
             textField.text=@"";
         }
     }else if (indexPath.row==4)
     {
         if ([[dataDic allKeys] containsObject:@"purpose"]) {
             textField.text= [dataDic objectForKey:@"purpose"];
             
         }else
         {
             textField.text=@"";
         }
     }else if (indexPath.row==5)
     {
         if ([[dataDic allKeys] containsObject:@"remark"]) {
             textField.text= [dataDic objectForKey:@"remark1"];
             
         }else
         {
             textField.text=@"";
         }
     }
    

    if(WindowWidth==320)
    {
        [textField bk_addEventHandler:^(UITextField *tfd) {
            
            NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:self.dataAr[indexPath.section]];
            //移除表情
            if ([CClass stringContainsEmoji:textField.text]) {
                textField.text=[textField.text substringToIndex:textField.text.length-2];
                return;
            }


            if (indexPath.row==0) {
                [dic setObject:tfd.text forKey:@"name"];
                
            }else if (indexPath.row==1)
            {
                [dic setObject:tfd.text  forKey:@"spec"];
                
            }else if (indexPath.row==2)
            {
                [dic setObject:tfd.text  forKey:@"count"];
                
            }else if (indexPath.row==3)
            {
                [dic setObject:tfd.text  forKey:@"total_price"];
                if (_dataAr.count==1) {
                    
                    _totalLab.text=[NSString stringWithFormat:@"合计（元）：%.2f",[tfd.text doubleValue]];
                    
                }else
                {
                    double totalDoubleDetele = 0.0;
                    for (int i=0; i<_dataAr.count; i++) {
                        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:self.dataAr[i]];
                        //名称
                        if ([[dic allKeys] containsObject:@"total_price"]) {
                            
                            if ([[dic objectForKey:@"total_price"] isEqualToString:@""]) {
                            }else
                            {
                                totalDoubleDetele+=[[dic objectForKey:@"total_price"] doubleValue];
                            }
                        }else
                        {
                            
                            
                        }
                    }
                    _totalLab.text=[NSString stringWithFormat:@"合计（元）：%.2f",totalDoubleDetele];
                }
                
                
            }else if (indexPath.row==4)
            {
                [dic setObject:tfd.text  forKey:@"purpose"];
                
            }else if (indexPath.row==5)
            {
                [dic setObject:tfd.text  forKey:@"remark"];
                
            }
            
            [self.dataAr replaceObjectAtIndex:indexPath.section withObject:dic];
            

        } forControlEvents:UIControlEventEditingChanged];

        

    }else
    {
        
        [textField setBk_shouldChangeCharactersInRangeWithReplacementStringBlock:^BOOL(UITextField *tfd, NSRange range, NSString * str) {
            if ([[[UITextInputMode currentInputMode]primaryLanguage] isEqualToString:@"emoji"]) {
                return NO;
            }
            NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:self.dataAr[indexPath.section]];
            
            NSString *textString = [tfd.text stringByReplacingCharactersInRange:range withString:str];
            
            if (indexPath.row==0) {
                
                [dic setObject:textString forKey:@"name"];
                
            }else if (indexPath.row==1)
            {
                //规格
                [dic setObject:textString forKey:@"spec"];
                
            }else if (indexPath.row==2)
            {
                
                [dic setObject:textString forKey:@"count"];
                
            }else if (indexPath.row==3)
            {
                if(((str.intValue<0) || (str.intValue>10))){
                    //MyLog(@"====%@",string);
                    if ((![str isEqualToString:@"."])) {
                        return NO;
                    }
                    return NO;
                }
                
                NSMutableString * futureString = [NSMutableString stringWithString:tfd.text];
                [futureString  insertString:str atIndex:range.location];
                NSInteger dotNum = 0;
                NSInteger flag=0;
                const NSInteger limited = 2;
                if((int)futureString.length>=1){
                    
                    if([futureString characterAtIndex:0] == '.'){//the first character can't be '.'
                        return NO;
                    }
                    if((int)futureString.length>=2){//if the first character is '0',the next one must be '.'
                        if(([futureString characterAtIndex:1] != '.'&&[futureString characterAtIndex:0] == '0')){
                            return NO;
                        }
                    }
                }
                NSInteger dotAfter = 0;
                for (int i = (int)futureString.length-1; i>=0; i--) {
                    if ([futureString characterAtIndex:i] == '.') {
                        dotNum ++;
                        dotAfter = flag+1;
                        if (flag > limited) {
                            return NO;
                        }
                        if(dotNum>1){
                            return NO;
                        }
                    }
                    flag++;
                }
                if(futureString.length - dotAfter > 8){
                    return NO;
                }
                
                [dic setObject:textString forKey:@"total_price"];
                
                
            }else if (indexPath.row==4)
            {
                [dic setObject:textString forKey:@"purpose"];
                
            }else if (indexPath.row==5)
            {
                //备注
                
                [dic setObject:textString forKey:@"remark"];
            }
            
            [self.dataAr replaceObjectAtIndex:indexPath.section withObject:dic];
            
            
            return YES;
            
        }];
    }
  
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    
    
    return cell;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
   
    return 50;

}

- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section==0) {
        UIView *headView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, WindowWidth, 50)];
        headView.backgroundColor=C(@"f0f0f0");
        UILabel *titleLab=[[UILabel alloc]initWithFrame:CGRectMake(10, 0, WindowWidth-30, 50)];
        titleLab.text=[NSString stringWithFormat:@"明细（%d）",section+1];
        titleLab.font=F(14);
        titleLab.textColor=C(@"7d7d7d");
        [headView addSubview:titleLab];
        return headView;
    }else
    {
        UIView *headView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, WindowWidth, 50)];
        headView.backgroundColor=C(@"f0f0f0");
        UILabel *titleLab=[[UILabel alloc]initWithFrame:CGRectMake(10, 0, WindowWidth-30-50, 50)];
        titleLab.text=[NSString stringWithFormat:@"明细（%d）",section+1];
        titleLab.font=F(14);
        titleLab.textColor=C(@"7d7d7d");
        [headView addSubview:titleLab];
        
        UIButton *deleteBtn=[UIButton buttonWithType:UIButtonTypeCustom];
        deleteBtn.frame=CGRectMake(WindowWidth-50-15, 0, 50, 50);
        [deleteBtn setTitle:@"删除" forState:UIControlStateNormal];
        deleteBtn.titleLabel.font=F(14);
        [headView addSubview:deleteBtn];
        [deleteBtn setTitleColor:MainColor forState:UIControlStateNormal];
        [deleteBtn bk_addEventHandler:^(id sender) {
            _sectionNum--;
            [_dataAr removeObjectAtIndex:section];
            [_table reloadData];
            double totalDoubleDetele = 0.0;
            for (int i=0; i<_dataAr.count; i++) {
                NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:self.dataAr[i]];
                //名称
                if ([[dic allKeys] containsObject:@"total_price"]) {
                    
                    if ([[dic objectForKey:@"total_price"] isEqualToString:@""]) {
                    }else
                    {
                    totalDoubleDetele+=[[dic objectForKey:@"total_price"] doubleValue];
                    }
                }else
                {
                   
                    
                }
            }
            _totalLab.text=[NSString stringWithFormat:@"合计（元）：%.2f",totalDoubleDetele];

        } forControlEvents:UIControlEventTouchUpInside];
        return headView;
    }

    
    
}
- (UIView*)footTableView
{
    
    UIView *view =[[UIView alloc]initWithFrame:CGRectMake(0, 0, WindowWidth, 80+35+150)];
    view.backgroundColor =C(@"f0f0f0");
    UILabel *lab=[[UILabel alloc]initWithFrame:CGRectMake(10, 5, WindowWidth-15, 35)];
    lab.textColor=C(@"c6c6c6");
    lab.font=F(13);
    lab.text=@"如有多类物品，点击“增加明细”按钮";
    [view addSubview:lab];
    UIImage *img=[UIImage imageNamed:@"Ico_sample_add"];
    UIView *bgView =[[UIView alloc]initWithFrame:CGRectMake(0, 40, WindowWidth, 40)];
    bgView.backgroundColor =[UIColor whiteColor];
    [view addSubview:bgView];
    
    UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake((WindowWidth-70)/2, (40-img.size.height)/2, img.size.width, img.size.height)];
    imageView.userInteractionEnabled=YES;
    imageView.image=img;
    [bgView addSubview:imageView];
    UILabel *addLab =[[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(imageView.frame)+4, 0, 70, 40)];
    addLab.text=@"增加明细";
    addLab.font =F(14);
    addLab.textColor=C(@"666666");
    addLab.userInteractionEnabled=YES;
    [bgView addSubview:addLab];
    [bgView bk_whenTapped:^{
        _sectionNum++;
        [_dataAr addObject:@{}];

        //局部section刷新
        [_table insertSections:[NSIndexSet indexSetWithIndex:_sectionNum] withRowAnimation:UITableViewRowAnimationNone];
    }];
     _totalLab=[[UILabel alloc]initWithFrame:CGRectMake(10,80, WindowWidth-15, 35)];
    _totalLab.textColor=MainColor;
    _totalLab.font=F(14);
    _totalLab.text=@"合计（元）：0.00";
    [view addSubview:_totalLab];
    return view;
    
}

//去掉粘合性
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView ==_table)
    {
        CGFloat sectionHeaderHeight = 40;
        if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
            scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
        } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
            scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
        }
    }

}
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
         //显示下一个
    [_table focusNextTextField];

    return YES;
}

@end
